package edu.sdufe.service.impl;

import edu.sdufe.dao.StudentMapper;
import edu.sdufe.pojo.Condition;
import edu.sdufe.pojo.Student;
import edu.sdufe.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public List<Student> queryAllStudents() {
        return studentMapper.selectAll();
    }

    @Override
    public List<Student> queryStudentsByCondition(Condition condition) {
        return studentMapper.selectByCondition(condition);
    }

    @Override
    @Transactional
    public int addStudent(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        int result = studentMapper.insert(student);
        if (result > 0) {
            updateRanksByScore(); // 添加成功后更新排名
        }
        return result;
    }

    @Override
    @Transactional
    public int updateStudent(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        int result = studentMapper.update(student);
        if (result > 0) {
            updateRanksByScore(); // 更新成功后更新排名
        }
        return result;
    }

    @Override
    @Transactional
    public int deleteStudent(Integer id) {
        int result = studentMapper.delete(id);
        if (result > 0) {
            updateRanksByScore(); // 删除成功后更新排名
        }
        return result;
    }

    @Override
    public int updateStudentRank(Integer id, Integer newRank) {
        return studentMapper.updateRank(id, newRank);
    }

    @Override
    public List<Student> queryStudentsByRankRange(Integer minRank, Integer maxRank) {
        return studentMapper.selectByRankRange(minRank, maxRank);
    }

    @Override
    public void updateRanksByScore() {
        // 调用Mapper中的SQL语句更新排名
        studentMapper.updateRanksByScore();
    }
}


